package gitobject;

import sha1.SHA1;
import zlib.ZLibUtils;

import java.io.*;

public class Blob extends GitObject{
    private static final long serialVersionUID = -2232888244746017709L;
    public static String deleteKey = String.format("%040d", 0);
    public String getFmt(){
        return fmt;
    }
    public String getMode(){
        return mode;
    }
    public String getPath() {
        return path;
    }
    public String getValue(){
        return value;
    }
    public String getKey() { return key; }
    public Blob(){};
    /**
     * Constructing blob object from a file
     * @param file
     * @throws Exception
     */
    public Blob(File file) throws Exception {
        fmt = "blob";
        mode = "100644";
        value = getValue(file);
        name = file.getName();
        key = genKey(file);
        //compressWrite();
    }

    public Blob(String name){
        fmt = "blob";
        mode = "100644";
        this.name = name;
        key = deleteKey;
    }

    public void setKeyToDelete(){
        key = deleteKey;
    }
    /**
     * Write this blob to commit history
     * @throws Exception
     */
    public boolean writeBlob() throws Exception{
        return compressWrite();
    }

    /**
     * Deserialize a blob object from an existed hash file in .jit/objects.
     * @param Id
     * @throws IOException
     */
    public static Blob deserialize(String Id) throws IOException {
        Blob blob = null;
        try{
            /**
             * Todo: Add your code here.
             */
            byte[] bytes = deCompress(Id);
            if(bytes == null) return null;
            ByteArrayInputStream in = new ByteArrayInputStream(bytes);
            ObjectInputStream file = new ObjectInputStream(in);
            blob = (Blob)file.readObject();
            file.close();
        }catch (Exception e){
            e.printStackTrace();
        }
        /* Todo: You should delete the return statement before you start. */
        return blob;
    }

    /**
     * Generate key from file.
     * @param file
     * @return String
     * @throws Exception
     */
    public String genKey(File file) throws Exception {
        key = SHA1.getHash(file);
        return key;
    }

    /**
     * return when this blob deleted in repository.
     * @return
     */
    @Override
    public String toString(){
        return "100644 blob " + key;
    }
}
